﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine;
using Engine.Attributes;
using System.ComponentModel;
using System.Reflection;

namespace Engine
{
	
	public abstract class UserCodedComponent: IComponent
	{
		private static int instanceNum = 0;

		[Config]
		public string Name { get; set; }

		public UserCodedComponent()
		{
			// assign a name as the class name of the object plus a unique number
			string realClassName = this.GetType().ToString();
			Name = realClassName + "_" + instanceNum.ToString();
			instanceNum++;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns>an array of all InPort objects defined on this Component, as the generics-free IInPort type</returns>
		public IInPort[] GetInPorts()
		{
			Type realType = this.GetType();
			FieldInfo[] fields = realType.GetFields();
			List<IInPort> iports = new List<IInPort>();
			foreach (FieldInfo field in fields)
			{
				if(field.FieldType.GetInterface("IInPort") != null)
				{
					iports.Add((IInPort)field.GetValue(this));
				}
			}
			return iports.ToArray();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns>an array of all OutPort objects defined on this Component, as the generics-free IOutPort type</returns>
		public IOutPort[] GetOutPorts()
		{
			Type realType = this.GetType();
			FieldInfo[] fields = realType.GetFields();
			List<IOutPort> oports = new List<IOutPort>();
			foreach (FieldInfo field in fields)
			{
				if (field.FieldType.GetInterface("IOutPort") != null)
				{
					oports.Add((IOutPort)field.GetValue(this));
				}
			}
			return oports.ToArray();
		}

		// empty default Reset
		public virtual void Reset() { }
    }
}
